package com.bfxy.rabbit.common.convert;

import com.google.common.base.Preconditions;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.support.converter.MessageConversionException;
import org.springframework.amqp.support.converter.MessageConverter;

/**
 * $RabbitMessageConvert 设计模式-装饰者模式/静态代理
 */
public class RabbitMessageConvert implements MessageConverter {

    private final GenericMessageConverter genericMessageConverter;

//    private final String defaultExpire = String.valueOf(24 * 60 * 60 * 1000);

    public RabbitMessageConvert(GenericMessageConverter genericMessageConverter) {
        Preconditions.checkNotNull(genericMessageConverter);
        this.genericMessageConverter = genericMessageConverter;
    }

    @Override
    public Message toMessage(Object object, MessageProperties messageProperties) throws MessageConversionException {
        // 可以通过messageProperties添加符合自己的业务逻辑的装饰
//        messageProperties.setExpiration(defaultExpire);
        com.bfxy.rabbit.api.model.Message message = (com.bfxy.rabbit.api.model.Message) object;
        // 设置延迟消息时间
        messageProperties.setDelay(message.getDelayMills());
        return this.genericMessageConverter.toMessage(object, messageProperties);
    }

    @Override
    public com.bfxy.rabbit.api.model.Message fromMessage(Message message) throws MessageConversionException {
        return (com.bfxy.rabbit.api.model.Message) this.genericMessageConverter.fromMessage(message);
    }

}
